<?php
/**
 * Created by PhpStorm.
 * User: zq
 * Date: 2018/2/10
 * Time: 09:10
 */

namespace Helper;

use UserModel;
use ClassesModel;

class G {

    const ADMIN   = 1;
    const TEACHER = 2;
    const STUDENT = 3;
    const PARENT  = 4;

    public static function config($filename = 'application', $module = '') {
        if (!$module) {
            $config = new \Yaf\Config\Ini(APP_PATH . "/config/{$filename}.ini");
        } else {
            $config = new \Yaf\Config\Ini(APP_PATH . "/config/{$filename}.ini", $module);
        }
        return $config;
    }


    public static function isValidMobile($mobile) {
        return preg_match("/1[34578]{1}\d{9}$/", $mobile);
    }

    /**
     * 6～16位，且数字字母组合
     * @param $password
     * @return false|int
     */
    public static function isValidPassword($password) {
//        return preg_match("/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/", $password);

        $len = strlen($password);

        if ($len < 6 || $len > 16) {
            return false;
        }

        $exista = preg_match("/[a-zA-z]+/", $password);
        $existn = preg_match("/[0-9]+/", $password);

        if (!($exista && $existn)) {
            return false;
        }

        return true;
    }

    public static function isValidSmscode($smscode) {
        return preg_match("/[0-9]{4}/", $smscode);
    }

    public static function generateSmscode($len = 4) {
        $chars    = ["0", "1", "2", "3", "5", "6", "7", "8", "9"];
        $charslen = count($chars) - 1;
        shuffle($chars);
        $arr = [];
        for ($i = 0; $i < $len; $i++) {
            $arr[] = $chars[mt_rand(0, $charslen)];
        }
        return implode('', $arr);
    }

    public static function md5Password($password) {
        return md5(sha1($password) . '0a38NW4X7ZRTfAIzoEKiSpCyhVBcJO1j6xgw2PlH');
    }

    public static function generateToken($mobile, $password, $salt, $usertype = G::TEACHER) {
        $str = "{$mobile}_{$usertype}_{$password}_{$password}";
        return md5(md5($str) . '_' . $salt);
    }

    /**
     * @param $mobile
     * @param $message
     * @return bool
     */
    public static function sendSmsMessage($mobile, $smscode, $usertype = G::TEACHER) {
//        $ret = Sms::i()->send($mobile, $smscode);
        $config          = G::config('api', 'sms');
        $url             = $config->url;
        $params          = [
            'mobile'    => $mobile,
            'smscode'   => $smscode,
            'timestamp' => time(),
            'usertype'  => $usertype ?? 0,
        ];
        $token           = G::apiToken($params);
        $params['token'] = $token;

        $ret = HttpCurl::i()->post($url, $params)->response;
        $res = json_decode($ret);
        if ($res->code != 200) {
            return false;
        }

        if ($res->data->status != 1) {
            return false;
        }
        return true;

//        if (isset($ret->Code) && strtolower($ret->Code) == 'ok') {
//            $status = 1;
//        } else {
//            $status = 2;
//        }
//
//        $return = json_encode($ret);
//
//        //记录log
//        $data = [
//            'mobile' => $mobile,
//            'content' => $smscode,
//            'return' => $return,
//            'type' => $usertype,
//            'status' => $status,
//            'create_time' => time(),
//        ];
//
//        \SmsMessageModel::add($data);
//        return $status == 1 ? true : false;
    }

    /**
     * 获取IP地址
     */
    public static function ipAddress() {
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $cip = $_SERVER["HTTP_CLIENT_IP"];
        } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } elseif (!empty($_SERVER["REMOTE_ADDR"])) {
            $cip = $_SERVER["REMOTE_ADDR"];
        } else {
            $cip = "127.0.0.1";
        }
        return $cip;
    }


    public static function apiToken($params) {
        $config = G::config('api', 'common');
        $secret = $config->secret;

        ksort($params);
        $str = http_build_query($params);
        return md5(md5($str) . $secret);
    }


    public static function mkDirs($dir, $mode = 0777) {
        if (is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }
        if (!self::mkDirs(dirname($dir), $mode)) {
            return false;
        }

        return @mkdir($dir, $mode);
    }


    /**
     * 生成uuid
     * @param int $usertype
     * @return string
     */
    public static function generateUuid($usertype = G::TEACHER) {

        $i = 0;
        //注册，生成uuid
        do {
            $uuid  = ($usertype + 5) . G::generateSmscode(7);
            $exist = UserModel::exists($uuid);
            //尝试10次
            if (++$i >= 10) {
                $uuid = 0;
                break;
            }

        } while ($exist);

        return $uuid;
    }


    /**
     * 生成班级号
     * @return string
     */
    public static function generateClassNo() {
        $exist = false;
        $i     = 0;
        do {
            $classNo = G::generateSmscode(7);
            if ($classNo >= 1000000) {
                $exist = ClassesModel::exists($classNo);
            }

            if (++$i >= 10) {
                $classNo = 0;
                break;
            }

        } while ($exist || $classNo < 1000000);

        return $classNo;
    }

    /**
     * 从数组中随机删除一个元素，并返回该元素
     * @param $array
     * @return mixed
     */
    public static function spliceRandArray(&$array) {

        $rand_keys = array_rand($array);
        return array_splice($array, $rand_keys, 1)[0];
    }

}